package com.nand.module.function.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.HttpParams;
import com.nand.library.base.base.BaseActivity;
import com.nand.library.base.bean.ResponseBean;
import com.nand.library.base.http.MyCallback;
import com.nand.library.base.http.OkGoUtils;
import com.nand.library.base.utils.SpUtils;
import com.nand.module.function.R;
import com.nand.module.function.adapter.IqcLldAdapter;
import com.nand.module.function.bean.EqDatailBean;
import com.nand.module.function.bean.IqcListBean;
import com.nand.module.function.bean.ManageBean;
import com.nand.module.function.constant.URL;
import com.nand.module.function.utils.LogUtils;
import com.nand.module.function.utils.SpacesItemDecoration;
import com.nand.module.function.view.CustomPartShadowPopupView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * created by 86185
 * on 2019/12/30
 */
@Route(path = "/function/iqc")
public class IqcListAtivity extends BaseActivity {
    private static final int IQC_LLD_CODE = 0; //IQC来料单
    private static final int IQC_JYD_CODE = 1; //IQC检验单
    private static final int IQC_CLD_CODE = 2; //不合格品处理单
    private RecyclerView mRecycler;
    private IqcLldAdapter mRecyclerAdapter;
    private int type;
    private String Url = "";
    private TextView mHeadLine;
    private ImageView mIvAdd;
    private TextView mTvManage;
    private SmartRefreshLayout swipeRefres;
    private HttpParams param;
    private TextView mTvSj;
    private int page;//加载页数
    private LinearLayout llEmpty;
    private int userId;
    private String oid;

    private CheckBox cbValue1;
    private CheckBox cbValue2;
    private RelativeLayout relativeLayout1;

    private String[] dataValue1;
    private String[] dataValue2;
    private CustomPartShadowPopupView popupViewResult;
    private CustomPartShadowPopupView popupViewType;
    private int typePosition = 0;
    private int resultPosition = 0;
    private String valueParam1;
    private String valueParam2;

    @Override
    protected int initLayout() {
        return R.layout.activity_iqc_lld;
    }

    @Override
    protected void initView() {
        page = 1;
        type = getIntent().getExtras().getInt("type");
        userId = SpUtils.readInt(this, "userId", 0);
        mRecycler = findViewById(R.id.recycler);
        mHeadLine = findViewById(R.id.tv_headline);
        llEmpty = findViewById(R.id.ll_empty);
        llEmpty.setVisibility(View.GONE);

        cbValue1 = findViewById(R.id.cb_value1);
        cbValue2 = findViewById(R.id.cb_value2);
        relativeLayout1 = findViewById(R.id.relative_2);

        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerAdapter = new IqcLldAdapter(this,type);
        //mRecycler.addItemDecoration(new DividerGridItemDecoration(this, 18, R.color.color_f4));
        int space = 20;
        mRecycler.addItemDecoration(new SpacesItemDecoration(space));
        mRecycler.setAdapter(mRecyclerAdapter);
        mRecyclerAdapter.setOnItemClickListener(new IqcLldAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (type){
                    case IQC_LLD_CODE:
                        oid = list.get(position).getOid();
                        Intent intent = new Intent(IqcListAtivity.this, IqcDetailsActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", IQC_LLD_CODE);
                        bundle.putString("oid", oid);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, 1);
                        break;
                    case IQC_JYD_CODE:
                        oid = list.get(position).getOid();
                        int state = list.get(position).getState();
                        if (0 == state){ //已送检
                            Intent intent2 = new Intent(IqcListAtivity.this, IqcCheckoutActivity.class);
                            Bundle bundle2 = new Bundle();
                            bundle2.putInt("type", state);
                            bundle2.putString("oid", oid);
                            intent2.putExtras(bundle2);
                            startActivityForResult(intent2, 1001);
                        }else {  //已检验
                            Intent intent2 = new Intent(IqcListAtivity.this, IqcCheckoutActivity.class);
                            Bundle bundle2 = new Bundle();
                            bundle2.putInt("type", state);
                            bundle2.putString("oid", oid);
                            intent2.putExtras(bundle2);
                            startActivityForResult(intent2, 1001);
                        }
                           // ARouter.getInstance().build("/function/iqc/checkout").withString("type",s ).navigation();

                        break;
                    case IQC_CLD_CODE:
                        oid = list.get(position).getOid();
                        ARouter.getInstance().build("/function/iqc/details").withString("oid",oid).withInt("type",IQC_CLD_CODE).navigation();
                }
            }
        });

        mTvManage = findViewById(R.id.tv_manage);
        mIvAdd = findViewById(R.id.iv_add);
        mTvSj = findViewById(R.id.tv_sj);

        swipeRefres = findViewById(R.id.swipe_refres);
        swipeRefres.setEnableRefresh(true);//是否启用下拉刷新功能
        swipeRefres.setEnableLoadMore(true);//是否启用上拉加载功能
        swipeRefres.autoRefresh();
        swipeRefres.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        swipeRefres.setRefreshHeader(new ClassicsHeader(this));
        swipeRefres.setRefreshFooter(new ClassicsFooter(this));

        swipeRefres.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                param = new HttpParams();
                page = 1;
                param.put("current", "1");
                param.put("size", "10");
                //down(false);
                selectListCondition(false);
            }
        });
        swipeRefres.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //刷新需要执行操作
                page++;
                param = new HttpParams();
                param.put("current", String.valueOf(page));
                param.put("size", "10");
              //  down(false);
                selectListCondition(false);
            }
        });

        cbValue1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (type){
                    case 0://IQC来料单
                        showPopupViewResultList(view,dataValue1,getResources().getString(R.string.sx_yxj));
                        break;
                    case 1://IQC检验单
                        showPopupViewResultList(view,dataValue1,getResources().getString(R.string.sx_yxj));
                        break;
                    case 2: //不合格品处理单
                        showPopupViewResultList(view,dataValue1,getResources().getString(R.string.sx_zt));
                       // showPopupViewResultList(view,dataValue1,getResources().getString(R.string.sx_yxj));
                        break;
                }
            }
        });
        cbValue2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               // showPopupViewTypeList(view,dataValue2);
                switch (type){
                    case 0:
                        showPopupViewTypeList(view,dataValue2,getResources().getString(R.string.sx_zt));
                        break;
                    case 1:
                        showPopupViewTypeList(view,dataValue2,getResources().getString(R.string.sx_zt));
                        break;
                    case 2:

                        break;
                }
            }
        });
    }
    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list(iqc来料单(优先级)，iqc检验优先级)
     */
    private void showPopupViewResultList(View view, String[] data, final String value){
        if(popupViewResult==null){
            popupViewResult = (CustomPartShadowPopupView) new XPopup.Builder(activity)
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbValue1.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(activity));
            popupViewResult.setStringData(data, null);
            popupViewResult .setCheckedPosition(resultPosition);
            popupViewResult .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    resultPosition = position;
                    cbValue1.setText(position == 0 ? value:text);
                    page = 1;
                    selectListCondition(false);
                }
            });
        }
        popupViewResult.show();
    }

    /**
     *  @author ljp
     *  @time   14:11
     *  @describe 弹出筛选条件list(iqc来料单(状态)，iqc检验（优先级）,iqc不合格（状态）)
     */
    private void showPopupViewTypeList(View view, String[] data, final String value){
        if(popupViewType==null){
            popupViewType = (CustomPartShadowPopupView) new XPopup.Builder(activity)
                    .atView(view)
                    .autoOpenSoftInput(true)
                    .setPopupCallback(new SimpleCallback() {
                        @Override
                        public void onShow() {
                        }
                        @Override
                        public void onDismiss() {
                            cbValue2.setChecked(false);
                        }
                    })
                    .asCustom(new CustomPartShadowPopupView(activity));
            popupViewType.setStringData(data, null);
            popupViewType .setCheckedPosition(typePosition);
            popupViewType .setOnSelectListener(new CustomPartShadowPopupView.OnSelectListener() {
                @Override
                public void onSelect(int position, String text) {
                    typePosition = position;
                    cbValue2.setText(position == 0 ? value:text);
                    page = 1;
                    selectListCondition(false);
                }
            });
        }
        popupViewType.show();
    }
    /**
     *  @author ljp
     *  @time   10:06
     *  @describe 根据筛选条件查询数据
     */
    private void selectListCondition(boolean isFirst){
        param.clear();
        param.put("current", String.valueOf(page));
        param.put("size", "10");
            if (resultPosition > 0) {
                if (typePosition > 0) {
                    param.put(valueParam1, resultPosition - 1);
                    param.put(valueParam2, String.valueOf(typePosition - 1));
                } else {
                    param.put(valueParam1, resultPosition - 1);
                }
            } else {
                if (typePosition > 0) {
                    param.put(valueParam2, String.valueOf(typePosition - 1));
                }
            }
        down(isFirst);
    }
    private List<IqcListBean.DataListBean> list = new ArrayList<>();


    @Override
    protected void initData() {
        switch (type) {
            case IQC_LLD_CODE:
                Url = URL.QUERY_IQC_CHECK;
                mHeadLine.setText("来料单");
                cbValue1.setText("优先级");
                cbValue2.setText("状态");
                dataValue1 = getResources().getStringArray(R.array.iqc_priority_list);
                dataValue2 = getResources().getStringArray(R.array.iqc_incoming_state_list);
                valueParam1 = "priority";
                valueParam2 = "state";
                break;
            case IQC_JYD_CODE:
                Url = URL.IQC_PECTION_LIST;
                mHeadLine.setText("检验单");
                mTvManage.setVisibility(View.GONE);
                mIvAdd.setVisibility(View.GONE);
                cbValue1.setText("优先级");
                cbValue2.setText("状态");
                dataValue1 = getResources().getStringArray(R.array.iqc_priority_list);
                dataValue2 = getResources().getStringArray(R.array.iqc_test_state_list);
                valueParam1 = "priority";
                valueParam2 = "state";
                break;
            case IQC_CLD_CODE:
                Url = URL.QUERY_IQC_NG;
                mHeadLine.setText("不合格处理单");
                mTvManage.setVisibility(View.GONE);
                mIvAdd.setVisibility(View.GONE);
                relativeLayout1.setVisibility(View.GONE);
                cbValue1.setText("状态");
                dataValue1 = getResources().getStringArray(R.array.iqc_disqualified_state_list);
                valueParam1 = "state";
                break;
            default:
                break;
        }
        param = new HttpParams();
        param.put("current", "1");
        param.put("size", "10");
        down(true);
    }

    private int size = 0;
    private void down(final boolean isFirst) {
        LogUtils.e("down==param==="+param);
        OkGoUtils.getInstance().post(this, Url, param, 1, false, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (response.getCode() == 200) {
                    String data = response.getDataInfo().toString();
                    LogUtils.e("avv===onSuccess===="+data);
                    swipeRefres.finishLoadMore();
                    if (!isFirst)
                        swipeRefres.finishRefresh();

                    IqcListBean listBeans = JSON.parseObject(data, IqcListBean.class);
                    List<IqcListBean.DataListBean> dataList = listBeans.getDataList();
                    if (page != 1) {
                        if (dataList == null || dataList.size() == 0) {
                            swipeRefres.finishLoadMoreWithNoMoreData();
                        }
                    } else {
                        list.clear();

                        if (IQC_LLD_CODE == type){
                            for (int i = 0; i < dataList.size(); i++) {
                                int state = dataList.get(i).getState();
                                if (0 == state){
                                    size++;
                                }
                            }
                            if (size == 0) {
                                llEmpty.setVisibility(View.VISIBLE);
                            } else {
                                llEmpty.setVisibility(View.GONE);
                                size= 0;
                            }
                        }else {
                            if (dataList.size() == 0) {
                                llEmpty.setVisibility(View.VISIBLE);
                            } else {
                                llEmpty.setVisibility(View.GONE);
                            }
                        }

                    }
                    for (IqcListBean.DataListBean bean : dataList) {
                        list.add(bean);
                    }

                    mRecyclerAdapter.setData(list);
                } else {
                    showToast(response.getMsg());
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }

    public void onClickAdd(View view) {
        Intent intent = new Intent(this, IqcRegisterActivity.class);
        startActivityForResult(intent,1001);
    }

    private int manage = 0; //0管理 1完成
    public void onClickManage(View view){
        if (0 == manage){
            mTvSj.setVisibility(View.VISIBLE);
            mTvManage.setText("取消");
            manage = 1;
            mRecyclerAdapter.setShowCBox(1);
        }else {
            mTvSj.setVisibility(View.GONE);
            mTvManage.setText("送检");
            manage = 0;
            mRecyclerAdapter.setShowCBox(0);
        }

    }
    /**
     * 送检
     */
    int j;
    public void onClickInspect(View view){
        HttpParams paramsPost = new HttpParams();


        List<IqcListBean.DataListBean> checkItemsBean = mRecyclerAdapter.getCheckItemsBean();
        ArrayList<String> strings = new ArrayList<>();
        j = 0;

        for (int i = 0; i < checkItemsBean.size(); i++) {
            boolean select = checkItemsBean.get(i).getSelect();
            if (select){
                strings.add(checkItemsBean.get(i).getOid());
                j++;
            }
        }

        String[] arr = new String[strings.size()];
        for (int i = 0; i < strings.size(); i++) {
            arr[i] = strings.get(i);
        }
        paramsPost.put("iqcCheck", Arrays.toString(arr));
        paramsPost.put("fUserCreator", userId);
        LogUtils.e("aaaa===="+ Arrays.toString(arr));
        //LogUtils.e("aaaa===="+sb.toString());
        OkGoUtils.getInstance().post(this, URL.IQC_SEND_CHECK, paramsPost, 1, true, new MyCallback() {
            @Override
            public void onSuccess(ResponseBean response, int id) {
                if (200 == response.getCode()){
                    showToast("送检成功");
                    param = new HttpParams();
                    param.put("current", "1");
                    param.put("size", "10");
                    down(false);

                    mTvSj.setVisibility(View.GONE);
                    mTvManage.setText("送检");
                    manage = 0;
                    mRecyclerAdapter.setShowCBox(0);
                }else {
                    showToast("请选择送检条目");
                }
            }

            @Override
            public void onError(Throwable e, int id) {

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.e("zoule==========="+requestCode+"====="+resultCode);
        if (1001 == requestCode && 0 != resultCode){
            LogUtils.e("zoule==========="+requestCode);
            param.put("current", "1");
            param.put("size", "10");
            down(false);
        }

    }
}
